import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/page/view/component/UserIconView.dart';

import '../../pojo/ImPojo.dart';
import '../../util/ImSingleton.dart';
import '../bloc/WebRtcCubit.dart';
import '../view/component/LButton.dart';

class WebRtcVideoPage extends StatefulWidget {
  const WebRtcVideoPage({super.key});

  @override
  State<StatefulWidget> createState() => _WebRtcVideoState();
}

class _WebRtcVideoState extends State<WebRtcVideoPage> {

  bool isOverlay = false;     // 是否异常产生浮层

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
  }

  @override
  Widget build(BuildContext context) {
    var webRtcCubit = context.watch<WebRtcCubit>();
    print('webRtcCubit.state.videoList.length: ${webRtcCubit.state.mediaList.length}');

    return Scaffold(
        backgroundColor: Colors.black,
        body: Stack(
          alignment: AlignmentDirectional.bottomCenter,
          children: [
            _buildMainVideoView(context, webRtcCubit),
            // _buildLocalVideoView(context, webRtcCubit),
            _buildControlPane(context, webRtcCubit),
          ],
        )
    );
  }

  Widget _buildMainVideoView(BuildContext context, WebRtcCubit webRtcCubit) {
    return LoadingView(state: webRtcCubit.state.state, child: _buildVideo(context, webRtcCubit));
  }

  Widget _buildVideo(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    if (state.mediaList.isNotEmpty) {
      return RTCVideoView(
        state.mediaList[0].videoRenderer!,
        mirror: true,
        objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
      );
    } else {
      return RTCVideoView(
        state.localMediaData?.videoRenderer??RTCVideoRenderer(),
        mirror: true,
        objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
      );
    }
  }

  Widget _buildLocalVideoView(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    return Positioned(
      top: 30,
      right: 20,
      child: Container(
          width: 150,
          height: 150,
          color: Colors.white,
          child: state.mediaList.isNotEmpty ? RTCVideoView(
            state.localMediaData!.videoRenderer!,
            mirror: true,
            objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
          ) : const Text('error!!!!!!!!!!!!!!!', style: TextStyle(color: Colors.red),),
      )
    );
  }

  Widget _buildControlPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Positioned(
        top: 100,
        left: 10,
        right: 10,
        bottom: 30,
        child: Column(
          children: [
            if (webRtcCubit.state.mediaList.isEmpty) _buildUserIcon(context), // 用户头像
            _buildTipPane(context, webRtcCubit),                             // 连接提示信息栏
            const SizedBox(height: 20,),
            _buildSettingPane(context),                                      // 设置栏： 麦克风，扬声器， 摄像头
            const SizedBox(height: 20,),
            _buildClosePane(context, webRtcCubit),                           // 关闭控制行
          ],
        ));
  }

  // 用户头像
  Widget _buildUserIcon(BuildContext context) {
    ImUser loginUser = ImSingleton.getInstance().session.getData("LoginUser") as ImUser;
    return Center(
      child: Column(
        children: [
          UserIconView(user: loginUser),
          const SizedBox(
            height: 10,
          ),
          Text(loginUser.userName ?? loginUser.userId),
          const SizedBox(height: 30,)
        ],
      ),
    );
  }

  Widget _buildTipPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var isAccept = webRtcCubit.state.isAccept;
    var message = webRtcCubit.state.mediaList.isEmpty ? (isAccept ? '对方邀请您视频通话': '等待对方接受连接...') : '';
    return Expanded(
        child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [Text(message, style: const TextStyle(color: Colors.white54),)],
    ));
  }

  Widget _buildSettingPane(BuildContext context) {
    var webRtcCubit = context.read<WebRtcCubit>();
    var state = webRtcCubit.state;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        LButton(
          name: state.isCloseAudio ? '麦克风已关' : '麦克风已开',
          assetImage: state.isCloseAudio ? 'assets/webrtc-img/audio_close.svg' : 'assets/webrtc-img/audio.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchAudioEvent());
          },
        ),
        LButton(
          name: '扬声器已开',
          assetImage: 'assets/webrtc-img/speaker.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () { },
        ),
        LButton(
          name: state.isCloseVideo ? '摄像头已关': '摄像头已开',
          assetImage: state.isCloseVideo ? 'assets/webrtc-img/camera_close.svg' : 'assets/webrtc-img/camera.svg',
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchVideoEvent());
          },
        )
      ],
    );
  }

  Widget _buildClosePane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        GestureDetector(
          // 关闭按钮
          onTap: () {
            webRtcCubit.add(WebRtcCloseEvent(context));
          },
          child: const CircleAvatar(
            backgroundColor: Colors.white,
            child: Icon(
              Icons.close,
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
